package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Category;


import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.CategoryService;

import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;



    //套餐管理界面分页查询
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {
        log.info("page:{},pageSize:{}", page, pageSize);
        //构造分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Setmeal::getUpdateTime);     //按更新时间排序
        //name判断
        String trimName = StringUtils.trim(name);
        qw.like(StringUtils.isNotEmpty(trimName), Setmeal::getName, trimName);
        setmealService.page(setmealPage, qw);

        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        List<Setmeal> records = setmealPage.getRecords();
        ArrayList<SetmealDto> setmealDtosList = new ArrayList<>();

        records.forEach(record -> {
            Long categoryId = record.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            setmealDto.setCategoryName(categoryName);
            setmealDtosList.add(setmealDto);
        });
        setmealDtoPage.setRecords(setmealDtosList);
        return R.success(setmealDtoPage);
    }

    //新增套餐
    @Transactional
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto:{}", setmealDto);
        //保存setmeal套餐表,进行保存操作后,会将自动生成的主键值回填到实体对象的对应属性中
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        log.info("setmeal:{}", setmeal);
        setmealService.save(setmeal);

        Long setmealId = setmeal.getId();
        log.info("setmealId:{}", setmealId);

        //保存setmeal_dish表,setmealDto对象中的List<SetmealDish>没有setmeal_id,因为这个id是在setmeal表保存数据后才自动生成的主键id
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        setmealDishService.saveBatch(setmealDishes);

        return R.success("保存成功");
    }

    //点击修改,数据回显
    @GetMapping("{id}") //setmeal的主键id
    public R<SetmealDto> update(@PathVariable Long id) {
        log.info("setmealId:{}", id);
        SetmealDto setmealDto = new SetmealDto();
        //1.回显数据,1.1根据setmealId查询setmeal表,得到Setmeal对象,给SetmelDto赋值
        Setmeal setmeal = setmealService.getById(id);
        BeanUtils.copyProperties(setmeal, setmealDto);
        //1.2根据categoryId查询categoryName,给setmealDto中的categoryName属性赋值
        Long categoryId = setmeal.getCategoryId();
        Category category = categoryService.getById(categoryId);
        String categoryName = category.getName();
        setmealDto.setCategoryName(categoryName);
        //1.3根据setmealId查询setmeal_dish表,获取List<SetmealDish>,给SetmealDto中的list属性赋值
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(qw);
        setmealDto.setSetmealDishes(list);
        //1.4响应数据
        return R.success(setmealDto);
    }


    //保存修改
    @PutMapping
    //删除setMealCache名称下的所有缓存
    @CacheEvict(value = "setMealCache",allEntries = true)
    public R<String> updateSetmeal(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto:{}", setmealDto);
        //1.需要修改setmeal/setmeal_dish两张表1.1修改setmeal
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        setmealService.updateById(setmeal);
        //1.2修改setmeal_dish,先根据setmealId删除操作,再存储
        Long setmealId = setmeal.getId();
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishService.remove(qw);
        //1.3存储,需要补充setmealId属性
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        setmealDishService.saveBatch(setmealDishes);
        //响应
        return R.success("修改成功");
    }


    //删除/批量删除
    @DeleteMapping
    //删除setMealCache名称下的所有缓存
    @CacheEvict(value = "setMealCache",allEntries = true)
    public R<String> deleteBatch(String ids) {
        log.info("ids:{}", ids);
        //获取ids集合
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        //1根据ids删除setmeal数据,2根据ids删除setmeal_dish数据
        setmealService.removeBatchByIds(idList);
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.in(SetmealDish::getSetmealId, idList);
        setmealDishService.remove(qw);
        return R.success("删除成功");

    }

    //停售/起售/批量操作
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, String ids) {
        log.info("ids:{},status:{}", ids, status);
        //根据id集合修改status字段
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId, list);
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        setmealService.update(setmeal, qw);
        return R.success("修改成功");
    }

    @Cacheable(value = "setMealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    //根据categoryId和status查询setmeal_dish表
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //log.info("categoryId:{},status:{}", categoryId, status);
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId, setmeal.getCategoryId());
        qw.eq(setmeal.getStatus()!=null,Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }
}
